﻿using GalaSoft.MvvmLight.Messaging;
using SubVersionOne.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SubVersionOne
{
    /// <summary>
    /// Interaction logic for WorkItemsView.xaml
    /// </summary>
    public partial class WorkItemsView : UserControl
    {
        enum ViewType
        {
            Login,
            Settings,
            WorkItems
        }

        public string Message
        {
            get
            {
                return ViewModelLocator.MainStatic.GetMessage();
            }
        }
        public WorkItemsView()
        {
            InitializeComponent();
            this.DataContext = ViewModelLocator.MainStatic;
            this.Loaded += WorkItemsView_Loaded;
            this.settingsView.Saved += settingsView_Saved;
            this.settingsView.Canceled += settingsView_Canceled;
            //set initial view states.
            this.ToggleControlView(ViewType.Login);

            Messenger.Default.Register<LoginMessage>(this,OnLogin);
            Messenger.Default.Register<GenericMessage<string>>(this,PostMessage);
        }

        void settingsView_Canceled(object sender, EventArgs e)
        {
            this.ToggleControlView(ViewType.WorkItems);
        }

        void settingsView_Saved(object sender, EventArgs e)
        {
            this.ToggleControlView(ViewType.WorkItems);
           // this.statusMessage.Text = "Refreshing work items...";
            //DoLogin();
        }

        void WorkItemsView_Loaded(object sender, RoutedEventArgs e)
        {
            //if any stories have already been loaded, lets skip hitting the V1 server.
            if (ViewModelLocator.MainStatic.Items.Any())
            {
                EventLogger.Info("Found " + ViewModelLocator.MainStatic.Items.Count + " stories.");

                this.ToggleControlView(ViewType.WorkItems);
   
            }
            else
            {
                EventLogger.Info("Logging In.");
                  DoLogin();
            }
        }

        private async void DoLogin()
        {
            var pwd = PasswordManager.GetPassword();
            if (pwd != null)
            {
             
                ViewModelLocator.MainStatic.IsBusy = true;
                this.ToggleControlView(ViewType.WorkItems);
                var result = await VersionOneProxy.Login(pwd);
                if (result)
                {
                    OnLogin(new LoginMessage("success"));
                }
                else
                {
                    //new to  show the login form.
                    this.ToggleControlView(ViewType.Login);
                }
            }
            else
            {
                this.ToggleControlView(ViewType.WorkItems);
            }
        }

        /// <summary>
        /// posts a status updated.
        /// </summary>
        /// <param name="message"></param>
        private void PostMessage( GenericMessage<string> message)
        {
            //ensure whatever we do is on the UI thread.
            Dispatcher.Invoke(() =>
            {
                this.statusMessage.Text = message.Content;
            });
        }

        private  void OnLogin( LoginMessage message )
        {
            //ensure whatever we do is on the UI thread.
            Dispatcher.Invoke(() =>
                {
                    ViewModelLocator.MainStatic.IsBusy = false;
                    GetWorkItems();
            
                });


        }
        private async void GetWorkItems( )
        {
  
            this.statusMessage.Text = "Logged In As " + VersionOneProxy.LoggedInUser;
            this.loginView.Visibility = System.Windows.Visibility.Hidden;
            this.workItemGrid.Visibility = System.Windows.Visibility.Visible;
    
            ViewModelLocator.MainStatic.IsBusy = true;
            this.statusMessage.Text = "Loading WorkItems...";
            var items = await VersionOneProxy.GetWorkItems();
            ViewModelLocator.MainStatic.Items = new System.Collections.ObjectModel.ObservableCollection<ViewModel.SelectableItemViewModel>(items);
            LocalStorageProvider.Save(items);
            ViewModelLocator.MainStatic.IsBusy = false;
            this.statusMessage.Text = "Loaded " + items.Count + ( items.Select(x=>x.Children.Count).Sum() ) + " work items.";

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            EventLogger.Info("clicked ok button");
            ViewModelLocator.MainStatic.CloseDialog();
          
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.statusMessage.Text = "Refreshing work items...";
            DoLogin();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            PasswordManager.Clear();
            ViewModelLocator.MainStatic.Credentials = new VersionOneCredentials();
            this.DoLogin();
        }

        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            
       
        }


        /// <summary>
        /// toggle the visibility of the login view, settings view and workItems grid view
        /// <param name="view">the view to show</param>
        /// </summary>
        private void ToggleControlView(ViewType view )
        {
            switch( view)
            {
                case  ViewType.Login :

                    this.loginView.Toggle(true);
                    this.settingsView.Toggle(false);
                    this.workItemGrid.Toggle(false);
                    break;
                case ViewType.Settings:
                    this.loginView.Toggle(false);
                    this.settingsView.Toggle(true);
                    this.workItemGrid.Toggle(false);
                    break;
                case ViewType.WorkItems:
                    this.loginView.Toggle(false);
                    this.settingsView.Toggle(false);
                    this.workItemGrid.Toggle(true);
                    break;
            }
        }
        private void CrossFade(FrameworkElement source, FrameworkElement fadeTo, Action callback)
        {
            Storyboard b = new Storyboard();

            DoubleAnimation fade1 = new DoubleAnimation(0, TimeSpan.FromSeconds(1));
            DoubleAnimation fade2 = new DoubleAnimation(1, TimeSpan.FromSeconds(1));

            fade2.Completed += (s, e) =>
            {
                //this.stepsControl.Children.Remove(source);
                source.Visibility = System.Windows.Visibility.Hidden;
                if (callback != null)
                    callback();
            };

            b.Children.Add(fade1);
            b.Children.Add(fade2);

            Storyboard.SetTarget(fade1, source);
            Storyboard.SetTarget(fade2, fadeTo);

            Storyboard.SetTargetProperty(fade1, new PropertyPath("Opacity"));
            Storyboard.SetTargetProperty(fade2, new PropertyPath("Opacity"));

            b.Begin();
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            this.ToggleControlView(ViewType.Settings);
        }


    }


    public static class FrameworkElementExtension
    {
        public static void Toggle(this FrameworkElement element, bool visible)
        {
            if (visible)
            {
                element.Visibility = Visibility.Visible;
            }
            else
            {
                element.Visibility = Visibility.Hidden;
            }
        }
    }
}
